package com.jack.concurrency;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by zhang_j on 2019/12/6
 */
public class MyReadWriteLock {
    public static void main(String[] args) {
        final CachedData data = new CachedData();
        new Thread(()->data.processCachedData()).start();
        new Thread(()->data.processCachedData()).start();

        final ReadWriteLock lock = new ReentrantReadWriteLock();
        lock.readLock().lock();
        lock.writeLock().lock();
        System.out.println("未死锁");
    }
}

class CachedData{
    final ReadWriteLock lock = new ReentrantReadWriteLock();
    volatile boolean cacheValid = false;
    String data ;

    void processCachedData(){
        System.out.println("进入processCachedData");
        lock.readLock().lock();
        System.out.println("readLock上锁");
        if(!cacheValid){
            System.out.println("cacheValid为false");
            lock.readLock().unlock();
            System.out.println("readLock解锁");
            lock.writeLock().lock();
            System.out.println("writeLock上锁");
            try{
                if(!cacheValid){
                    System.out.println("cacheValid为false&data等于new");
                    data = "new";
                    cacheValid = true;
                }
                lock.readLock().lock();
                System.out.println("readLock上锁");
            }finally {
                lock.writeLock().unlock();
                System.out.println("writeLock解锁");
            }

        }

        try{
            String calS = "s"+data;
            System.out.println("calS"+calS);
        }finally {
            lock.readLock().unlock();
            System.out.println("readLock解锁");
        }
    }
}